<template>
  <div class="player-control"></div>
</template>

<script>
/*import APlayer from "APlayer";*/
var APlayer;
export default {
  props: {
    title: {},
    url: {}
  },
  data() {
    return {
      load: false
    };
  },
  computed: {
    music() {
      var data = {
        url: this.url,
        title: this.title || "sound",
        author: "x",
        pic: "x",
        lrc: "x"
      };
      if (
        this.url &&
        !this.url.startsWith("http:") &&
        this.url.startsWith("/")
      ) {
        data.url = "/" + this.url;
      }
      return data;
    }
  },
  watch: {
    url() {
      this.buildPlayer();
    }
  },
  methods: {
    play() {
      this.$nextTick(() => {
        //未加载时则设置加载状态事件
        if (!this.load) {
          this.$emit("loading", true);
        }
        this.$player.play();
      });
    },
    pause() {
      this.$nextTick(() => {
        this.$player.pause();
      });
    },
    buildPlayer() {
      if (!this.$el) return;
      if (this.$player) {
        this.$player.destroy();
      }
      this.load = false;
      this.$player = new APlayer({
        element: this.$el,
        narrow: false,
        autoplay: false,
        music: this.music
      });
      this.$player.pause();
      this.$player.on("canplay", () => {
        this.load = true;
        this.$emit("loading", false);
      });
      this.$player.on("error", () => {
        this.$emit("loading", false);
      });
    }
  },
  mounted() {
    if (this.url) {
      this.buildPlayer();
    }
  },
  beforeDestroy() {
    this.$player && this.$player.destroy();
  }
};
</script>

<style>

</style>
